package com.lengxf.milo.executor;

import com.lengxf.milo.model.WriteParam;
import com.lengxf.milo.model.WriteResult;
import com.lengxf.milo.node.NodeIdBuilder;
import org.eclipse.milo.opcua.sdk.client.api.UaClient;
import org.eclipse.milo.opcua.stack.core.types.builtin.DataValue;
import org.eclipse.milo.opcua.stack.core.types.builtin.NodeId;
import org.eclipse.milo.opcua.stack.core.types.builtin.StatusCode;
import org.eclipse.milo.opcua.stack.core.types.builtin.Variant;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public class WriteExecutor {

    public static WriteResult write(UaClient uaClient, WriteParam writeParam) {
        return write(uaClient, Collections.singletonList(writeParam)).get(0);
    }

    public static List<WriteResult> write(UaClient uaClient, List<WriteParam> writeParamList) {
        List<WriteResult> resultList = new ArrayList<>();
        List<NodeId> nodeIdList = writeParamList.stream()
                .map(e -> NodeIdBuilder.build(e.getIdentifier()))
                .collect(Collectors.toList());
        List<DataValue> dataValueList = writeParamList.stream()
                .map(e -> new DataValue(new Variant(e.getValue())))
                .collect(Collectors.toList());
        List<StatusCode> statusCodeList = uaClient.writeValues(nodeIdList, dataValueList).join();
        for (int i = 0; i < writeParamList.size(); i++) {
            resultList.add(new WriteResult(
                    writeParamList.get(i).getIdentifier(),
                    nodeIdList.get(i),
                    writeParamList.get(i).getValue(),
                    dataValueList.get(i),
                    statusCodeList.get(i)
            ));
        }
        return resultList;
    }

}
